#include "ct.h"
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <string>

// 读取文件内容
std::string readFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        throw std::runtime_error("Failed to open input file.");
    }

    std::ostringstream ct;
    ct << file.rdbuf();
    return ct.str();
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <input_file.ct>\n";
        return 1;
    }

    const std::string inputFilename = argv[1];
    const std::string outputCppFilename = "output.cpp";
    const std::string outputExeFilename = "output";

    try {
        // 读取 Cpp_Next 代码
        std::string simpleScriptCode = readFile(inputFilename);

        // 编译 Cpp_Next 代码为 C++
        Cpp_NextCompiler compiler(simpleScriptCode);
        compiler.compile(outputCppFilename);

        // 使用 g++ 编译生成的 C++ 代码
        std::string compileCommand = "g++ " + outputCppFilename + " -o " + outputExeFilename;
        if (system(compileCommand.c_str()) != 0) {
            throw std::runtime_error("Failed to compile C++ code.");
        }

        std::cout << "Compilation successful. Run ./" << outputExeFilename << " to execute the program.\n";
    } catch (const std::exception& e) {
        std::cerr << "Error: " << e.what() << '\n';
        return 1;
    }

    return 0;
}

